package com.sxbbc.plat.controller.jz;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.function.common.GetRest;
import com.function.common.RestResponse;
import com.sxbbc.common.basics.exceptions.ThrowJsonException;
import com.sxbbc.common.basics.exceptions.ThrowPageException;
import com.sxbbc.common.basics.rest.RestFactory;
import com.sxbbc.common.basics.utils.calculation.CalcuUtils;
import com.sxbbc.common.basics.utils.regular.RpxUtils;
import com.sxbbc.common.basics.utils.statics.FunctionUtils;
import com.sxbbc.common.basics.utils.statics.StaticUtils;
import com.sxbbc.common.core.dto.jz.ZTreeVo;
import com.sxbbc.common.core.entity.jz.Address;
import com.sxbbc.common.core.entity.jz.CCustomer;
import com.sxbbc.common.core.entity.jz.CustomerLevelInfo;
import com.sxbbc.common.core.service.IAddressService;
import com.sxbbc.common.core.service.ICCustomerService;
import com.sxbbc.common.core.service.ICustomerLevelInfoService;
import com.sxbbc.common.core.utils.BasePage;
import com.sxbbc.plat.common.CustomerMapping;
import com.sxbbc.plat.service.CustomerService;
import com.sxbbc.plat.util.PlatSession;
import com.sxbbc.plat.util.SystemLog;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author leehao
 * @description 会员管理 控制层
 * @date 2019-04-30 14:09
 */
@Controller
public class CustomerController {

    private Logger log = LogManager.getLogger(CustomerController.class);

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private ICCustomerService icCustomerService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private ICustomerLevelInfoService customerLevelInfoService;
    @Autowired
    private IAddressService addressService;

    /**
     * 会员列表页
     *
     * @return
     * @author Wahyee
     */
    @RequestMapping(value = CustomerMapping.SHOW_CUSTOMER)
    public ModelAndView showCustomerList() {
        List<CustomerLevelInfo> levelList = customerLevelInfoService.list(new QueryWrapper<>());
        ModelAndView view = new ModelAndView(CustomerMapping.SHOW_CUSTOMER);
        view.addObject("levelList", levelList);
        //编辑推荐人按钮显示特殊处理，有操作权限才能看到
        List<String> strs = PlatSession.getMenuUrl(request);
        boolean b = strs.contains(CustomerMapping.SHOW_PARENT_UPDATE);
        view.addObject("canShow", b);
        return view;
    }

    /**
     * 查询用户列表数据
     *
     * @param page     分页数据
     * @param customer 查询条件
     * @return
     * @author xiaoky
     */
    @RequestMapping(value = CustomerMapping.QUERY_CUSTOMER_LIST)
    @ResponseBody
    public com.sxbbc.common.basics.rest.RestResponse queryCustomerList(BasePage<CCustomer> page, CCustomer customer) {
        icCustomerService.queryCustomerList(page, customer);
        return RestFactory.success(page.getRecords(), page.getTotal());
    }

    /**
     * 冻结/解除冻结会员
     *
     * @param request session
     * @param id      会员id
     * @param status  状态
     * @return com.function.common.RestResponse
     * @author leehao
     */
    @RequestMapping(value = CustomerMapping.HANDLE_CUSTOMER_STATUS)
    @ResponseBody
    @SystemLog(methods = "变更会员状态", module = "会员管理")
    public RestResponse handleCustomerStatus(HttpServletRequest request, Integer id, Integer status) {
        return icCustomerService.handleCustomerStatus(id, status);
    }

    @RequestMapping(value = CustomerMapping.HANDLE_CUSTOMER_PASSWORD)
    @ResponseBody
    @SystemLog(methods = "重置会员密码", module = "会员管理")
    public RestResponse handleCustomerPassword(HttpServletRequest request, Integer id, Integer type) {
        return icCustomerService.handleCustomerPassword(id, type);
    }

    @RequestMapping(value = CustomerMapping.SHOW_CUSTOMER_LEVEL_ADJUST)
    public ModelAndView showCustomerLevelAdjust(Integer cid) {
        List<CustomerLevelInfo> levelList = customerLevelInfoService.list(new QueryWrapper<CustomerLevelInfo>());
        ModelAndView view = new ModelAndView(CustomerMapping.SHOW_CUSTOMER_LEVEL_ADJUST);
        view.addObject("cid", cid);
        view.addObject("levelList", levelList);
        return view;
    }

    @RequestMapping(value = CustomerMapping.HANDLE_CUSTOMER_LEVEL)
    @ResponseBody
    @SystemLog(methods = "修改会员等级或备注信息", module = "会员管理")
    public boolean handleCustomerLevel(HttpServletRequest request, CCustomer customer) {
        return icCustomerService.updateById(customer);
    }

    @RequestMapping(value = CustomerMapping.SHOW_CUSTOMER_EDIT_INFO)
    public ModelAndView showCustomerEdit(Integer cid) {
        Address address = new Address();
        address.setPid(StaticUtils.ADDRESS_COUNTRY);
        List<Address> addressList = addressService.queryAddressByParentId(address);
        ModelAndView view = new ModelAndView(CustomerMapping.SHOW_CUSTOMER_EDIT_INFO);
        view.addObject("cid", cid);
        view.addObject("addressList", addressList);
        return view;
    }

    @RequestMapping(value = CustomerMapping.HANDLE_CUSTOMER_EDIT)
    @ResponseBody
    @SystemLog(methods = "编辑会员信息", module = "会员管理")
    public RestResponse handleCustomerEdit(CCustomer customer) {
        RpxUtils rpxUtils = RpxUtils.getInstance();
        if (StringUtils.isNotBlank(customer.getLogin())) {
            if (!StringUtils.equals(rpxUtils.validPhone(customer.getLogin()), "")) {
                return GetRest.getFail(rpxUtils.validPhone(customer.getLogin()));
            }
            QueryWrapper<CCustomer> wrapper = new QueryWrapper<>();
            wrapper.eq("login", customer.getLogin()).ne("id", customer.getId());
            int count = icCustomerService.count(wrapper);
            if (count > 0) {
                return GetRest.getFail("账号必须是未注册的用户");
            }
        }
        if ("".equals(customer.getLogin())) {
            customer.setLogin(null);
        }

        icCustomerService.updateById(customer);
        return GetRest.getSuccess("操作成功");
    }

    /**
     * 会员备注
     *
     * @param cid
     * @return
     */
    @RequestMapping(value = CustomerMapping.SHOW_CUSTOMER_REMARK)
    public ModelAndView showCustomerRemark(Integer cid) {
        ModelAndView view = new ModelAndView(CustomerMapping.SHOW_CUSTOMER_REMARK);
        CCustomer customer = icCustomerService.getById(cid);
        view.addObject("customer", customer);
        return view;
    }

    /**
     * 会员等级页面
     *
     * @return org.springframework.web.servlet.ModelAndView
     * @author leehao
     */
    @RequestMapping(value = CustomerMapping.SHOW_CUSTOMER_LEVEL)
    public ModelAndView showCustomerLevel() {
        List<CustomerLevelInfo> list = customerLevelInfoService.list(null);
        ModelAndView view = new ModelAndView(CustomerMapping.SHOW_CUSTOMER_LEVEL);
        view.addObject("list", list);
        return view;
    }

    /**
     * 新增/编辑会员等级页面
     *
     * @param id 会员等级id
     * @return org.springframework.web.servlet.ModelAndView
     * @author leehao
     */
    @RequestMapping(value = CustomerMapping.SHOW_EDIT_CUSTOMER_LEVEL)
    public ModelAndView showCustomerLevelEdit(Integer id) {
        CustomerLevelInfo levelInfo = customerLevelInfoService.getById(id);
        ModelAndView view = new ModelAndView(CustomerMapping.SHOW_EDIT_CUSTOMER_LEVEL);
        view.addObject("level", levelInfo);
        return view;
    }

    /**
     * 新增/编辑会员等级
     *
     * @param imgUrl 等级图片
     * @param level  对象
     * @return com.function.common.RestResponse
     * @author leehao
     */
    @RequestMapping(value = CustomerMapping.EDIT_CUSTOMER_LEVEL)
    @ResponseBody
    @SystemLog(methods = "新增/编辑会员等级", module = "会员管理")
    public RestResponse editCustomerLevel(@RequestParam(required = false, name = "imgUrl") MultipartFile imgUrl,
                                          CustomerLevelInfo level) {
        if (StringUtils.isBlank(level.getName())) {
            return GetRest.getFail("请输入会员等级名称");
        }
        if (level.getPoint() == null) {
            return GetRest.getFail("请输入升级金额");
        }
        if (level.getUnderNum() == null) {
            return GetRest.getFail("请输入直推人数");
        }
        if (level.getScale() == null) {
            return GetRest.getFail("请输入自营商城消费抽成比例");
        }
        if (level.getBussinessScale() == null) {
            return GetRest.getFail("请输入会员业务提成收入比例");
        }
        boolean save = customerLevelInfoService.saveOrUpdate(level);
        if (!save) {
            throw new ThrowJsonException("保存会员等级失败");
        }
        return GetRest.getSuccess("保存成功");
    }

    @RequestMapping(value = CustomerMapping.SELECT_CUSTOMER_EXIST)
    @ResponseBody
    public RestResponse selectCustomerExist(String phone) {
        if (StringUtils.isBlank(phone)) {
            return GetRest.getFail("请输入手机号码");
        }
        CCustomer customer = new CCustomer();
        customer.setPhone(phone);
        CCustomer exist = icCustomerService.getCustomer(customer);
        if (exist == null) {
            return GetRest.getFail("该用户不存在，请先注册！");
        } else {
            return GetRest.getSuccess("恭喜，该用户存在！");
        }
    }

    /**
     * 修改推荐人页面
     *
     * @param cid
     * @return
     * @author Wahyee
     */
    @RequestMapping(value = CustomerMapping.SHOW_PARENT_UPDATE)
    public ModelAndView showParentUpdate(Integer cid) {
        ModelAndView view = new ModelAndView(CustomerMapping.SHOW_PARENT_UPDATE);
        CCustomer customer = icCustomerService.getById(cid);
        if (customer == null) {
            throw new ThrowPageException("用户数据信息获取失败，请稍后重试");
        }
        //推荐人信息 可为空
        CCustomer parent = icCustomerService.getById(customer.getParentid());
        view.addObject("customer", customer);
        view.addObject("parent", parent);
        return view;
    }

    /**
     * 修改用户推荐人
     *
     * @param cid      用户ID
     * @param parentid 推荐人用户ID
     * @return
     * @author Wahyee
     */
    @RequestMapping(value = CustomerMapping.UPDATE_PARENT)
    @ResponseBody
    public RestResponse updateParent(Integer cid, Integer parentid) {
        if (cid == null) {
            return GetRest.getFail("用户信息获取失败，请稍后重试");
        }
        if (parentid == null) {
            return GetRest.getFail("请填写推荐人信息");
        }
        if (CalcuUtils.getInstance().isEquals(cid, parentid)) {
            return GetRest.getFail("不能推荐自己");
        }

        CCustomer customer = icCustomerService.getById(cid);
        if (customer == null) {
            return GetRest.getFail("用户不存在");
        }
        QueryWrapper<CCustomer> wrapper = new QueryWrapper<>();
        wrapper.eq("parentid", cid);
        int num = icCustomerService.count(wrapper);
        if (customer.getParentid() == null && num > 0) {
            return GetRest.getFail("该用户为团队中的第一代，无法修改推荐人");
        }

        CCustomer parentCustomer = icCustomerService.getById(parentid);
        if (parentCustomer == null) {
            return GetRest.getFail("推荐人不存在");
        }
        if (parentCustomer.getGenes() != null) {
            String[] split = parentCustomer.getGenes().split(",");
            if (split != null && split.length > 0) {
                List<Integer> list = FunctionUtils.getIntegerList(split);
                if (list.contains(cid)) {
                    return GetRest.getFail("推荐人不能是当前会员的下级");
                }
            }
        }

//        QueryWrapper<CCustomer> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("parentid", cid);
//        int count = icCustomerService.count(queryWrapper);
//        if (count > 0) {
//            return GetRest.getFail("修改推荐人只能在当前会员处于最低一级时才可以修改");
//        }
        try {
            log.info("修改推荐人开始...");
            return customerService.updateParent(cid, parentid);
        } catch (Exception e) {
            log.info("修改推荐人异常：" + e.getMessage());
            return GetRest.getFail("修改失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户信息
     *
     * @param
     * @return
     * @author Wahyee
     */
    @RequestMapping(value = CustomerMapping.GET_CUSTOMER)
    @ResponseBody
    public RestResponse getCustomer(CCustomer customer) {
        customer = icCustomerService.getCustomer(customer);
        if (customer == null) {
            return GetRest.getFail("用户数据信息获取失败，请稍后重试");
        }
        return GetRest.getSuccess("", customer);
    }

    /**
     * 直推或间推会员页面
     *
     * @param
     * @param
     * @return
     */
    @RequestMapping(value = CustomerMapping.SHOW_EDIRECTORINDIRECT_CUSTOMER)
    public ModelAndView showDirectOrIndirectCustomer(BasePage<CCustomer> page, Integer parentid, Integer flag) {
        ModelAndView view = new ModelAndView(CustomerMapping.SHOW_EDIRECTORINDIRECT_CUSTOMER);
        view.addObject("flag", flag);
        view.addObject("parentid", parentid);
        return view;
    }

    /**
     * 查询我的团队
     *
     * @param
     * @param
     * @return
     */
    @RequestMapping(value = CustomerMapping.SHOW_MY_TEAM)
    public ModelAndView SELECT_MY_TEAM(Integer cid) {
        ModelAndView view = new ModelAndView(CustomerMapping.SHOW_MY_TEAM);
        view.addObject("cid", cid);
        return view;
    }

    /**
     * 获取我的团队用户信息
     *
     * @param
     * @return
     * @author Wahyee
     */
    @RequestMapping(value = CustomerMapping.SELECT_MY_TEAM)
    @ResponseBody
    public RestResponse selectMyTeam(Integer id) {
        List<ZTreeVo> result = customerService.selectMyTeam(id);
        return GetRest.getSuccess("", result);
    }
}
